let Placeholders = {
  IN: "多个请用英文逗号隔开",
  LIKE: "右侧模糊匹配"
};
let ValidateRules = {
  required: {
    required: true,
    message: "不能为空",
    trigger: "change"
  },
  requiredBlur: {
    required: true,
    message: "不能为空",
    trigger: "blur"
  },
  requiredTen: {
    required: true,
    max: 10,
    message: "[1-10]不能为空",
    trigger: "manual"
  },
  requiredTwenty: {
    required: true,
    message: "[1-20]不能为空",
    max: 20,
    trigger: "blur"
  },
  requiredMax: {
    required: true,
    max: 50,
    message: "[1-50]不能为空",
    trigger: "manual"
  },
  name: {
    required: true,
    max: 50,
    message: "名称[1-50]不能为空",
    trigger: "manual"
  },
  remark: {
    max: 200,
    message: "备注不能超过200个字",
    trigger: "change"
  },
  number: {
    type: "number",
    message: "必须为数字",
    trigger: "change"
  },
  url: {
    type: "url",
    message: "不符合网址格式",
    trigger: "change"
  },
  email: {
    type: "email",
    message: "不符合邮箱格式",
    trigger: "change"
  },
  password: {
    required: true,
    type: "string",
    pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/,
    message: "密码必须是8到16位数字与字母组合",
    trigger: "change"
  },
  code: {
    type: "string",
    pattern: /^[0-9A-Za-z]{1,10}$/,
    message: "编号必须是1到10位数字或字母",
    trigger: "change"
  },
  mobile: {
    type: "string",
    pattern: /^.{11,13}$/,
    message: "手机号或电话必须是11到13位数字",
    trigger: "change"
  },
  // 司机联系电话只能11位
  contact: {
    type: "string",
    pattern: /^.{11,11}$/,
    message: "手机号必须是11位数字",
    trigger: "change"
  },
  telephone: {
    required: true,
    type: "string",
    pattern: /^[0-9-]{11,13}$/,
    message: "手机号或电话必须是11到13位数字或-",
    trigger: "change"
  },
  phoneNumber: {
    required: true,
    type: "string",
    pattern: /^1[0123456789]\d{9}$/,
    message: "请输入手机号码，体验扫码签收",
    trigger: "change"
  },
  carriersCodeBlur: {
    required: true,
    message: "请输入公司编号",
    trigger: "blur"
  },
  carrierAbbrBlur: {
    required: true,
    message: "请输入承运方简称",
    trigger: "blur"
  },
  // quantity: {
  //   type: "number",
  //   pattern: /^[1-9]\d*|0$/,
  //   message: "数量必须是0或正整数",
  //   trigger: "change"
  // },
  // fileName: {
  //   required: true,
  //   type: "string",
  //   pattern: /^((?![\\/\:\*\?\"\<\>\|]).)*$/,
  //   message: "文件名不得包含特殊字符",
  //   trigger: "change"
  // },
  // longWidthHeight: {
  //   pattern: /^(\d{0,2})(\.(\d{0,2}))?$/g,
  //   message: "最多可输入2位整数，2位小数",
  //   trigger: "change"
  // },
  // integer: {
  //   pattern: /^\d{0,4}$/,
  //   message: "最多可输入4位整数，不可输入小数",
  //   trigger: "change"
  // },
  // weight: {
  //   pattern: /^(\d{0,5})(\.(\d{0,4}))?$/g,
  //   message: "最多可输入5位整数，4位小数",
  //   trigger: "change"
  // },
  // volume: {
  //   pattern: /^(\d{0,3})(\.(\d{0,6}))?$/g,
  //   message: "最多可输入3位整数，6位小数",
  //   trigger: "change"
  // },
  // price: {
  //   pattern: /^(\d{0,7})(\.(\d{0,2}))?$/g,
  //   message: "最多可输入7位整数，2位小数",
  //   trigger: "change"
  // }
};
ValidateRules.requiredNumber = [ValidateRules.required, ValidateRules.number];
ValidateRules.requiredEmail = [ValidateRules.required, ValidateRules.email];
ValidateRules.requiredMobile = [ValidateRules.required, ValidateRules.mobile];
ValidateRules.requiredTelephone = [
  ValidateRules.required,
  ValidateRules.telephone
];
// ValidateRules.requiredFileName = [
//   ValidateRules.required,
//   ValidateRules.fileName
// ];
ValidateRules.requiredUrl = [ValidateRules.required, ValidateRules.url];
// ValidateRules.requiredPrice = [ValidateRules.required, ValidateRules.price];
// ValidateRules.requiredVolume = [ValidateRules.required, ValidateRules.volume];
// ValidateRules.requiredWeight = [ValidateRules.required, ValidateRules.weight];

/**
 * 使用创建a标签下载文件
 * 正式环境地址  静态资源 需要添加 /v2/
 */
let tools = {};
tools.orderDownload = function (url, name = "") {
  console.log(url);
  let a = document.createElement("a");
  a.href = process.env.NODE_ENV === "production" ? `/v2${url}` : url;
  a.download = name;
  document.body.appendChild(a);
  a.target = "_blank";
  a.click(); // 点击下载
  document.body.removeChild(a);
};
export { Placeholders, ValidateRules, tools };

/**
 *
 * @param {Object} date: standard dateObject
 * @param {String} format: like ':' , '/' : '-'
 * @returns {String} '2017-04-09' or ''
 */
export function formatDate (time, format = "-") {
  if (!time) return "";
  let date = time;
  // if (date && date.constructor === String && date.indexOf('-') !== -1) date = date.replace(/\-/g, '/') // 兼容苹果内核
  // if (date.constructor === String && date.indexOf('.0') !== -1) date = date.substring(0, date.indexOf('.0')) // 兼容苹果内核
  date = typeof date === "string" ? new Date(date) : date;
  let currentMonth, currentDay;
  let month =
    (currentMonth = date.getMonth() + 1) > 9
      ? currentMonth
      : "0" + currentMonth;
  let day = (currentDay = date.getDate()) > 9 ? currentDay : "0" + currentDay;
  return date.getFullYear() + format + month + format + day;
}

export let pub = {
  treeTransArray: function (tree, key) {
    return tree
      .reduce(function (con, item) {
        var callee = arguments.callee;
        con.push(item);
        if (item[key] && item[key].length > 0) item[key].reduce(callee, con);
        return con;
      }, [])
      .map(function (item) {
        item[key] = [];
        return item;
      });
  }
};

/**
 * 树形扁平化
 * @param tree
 * @returns {*}
 */
export let treeToArray = (tree) => {
  let arr = [];
  const expanded = (datas) => {
    if (datas && datas.length > 0) {
      datas.forEach((x) => {
        arr.push(x);
        expanded(x.children);
      });
    }
  };
  expanded(tree);
  return arr;
};

/**
 * 根据节点id 查找关联的父节点函数体
 * @param tree   原数据
 * @param nodeId  子节点id
 * @returns {*}
 */
export const getTreeChildren = (tree, nodeId, config) => {
  const { children = "children", id = "id" } = config || {};
  const toFlatArray = (tree, parentIds) => {
    return tree.reduce((t, _) => {
      const child = _[children];
      return [
        ...t,
        parentIds ? { ..._, parentIds } : _,
        ...(child && child.length ? toFlatArray(child, _[id]) : [])
      ];
    }, []);
  };

  const getIds = (flatArray) => {
    let ids = [nodeId];
    let child = flatArray.find((_) => _[id] === nodeId);
    while (child && child.parentIds) {
      ids = [child.parentIds, ...ids];
      child = flatArray.find((_) => _[id] === child.parentIds);
    }
    return ids;
  };
  return getIds(toFlatArray(tree));
};

/**
 * 编辑器配置预参数赋值
 * @param source   原数据
 * @param transform  预参数
 * @returns {*}
 */
export const transformData = (source = {}, transform) => {
  // console.log("Transform :", transform)
  return source
  // if (!transform) {
  //   return {};
  // }
  // let target = {};
  // if (transform instanceof Function) {
  //   return transform(source) || {};
  // } else if (transform instanceof Object) {
  //   for (let [name, alias] of Object.entries(transform)) {
  //     if (alias && typeof alias === "string" && alias.includes(".")) {
  //       target[name] =
  //         source[alias.substring(0, alias.indexOf("."))][
  //         alias.substring(alias.indexOf(".") + 1, alias.length)
  //         ];
  //     } else {
  //       target[name] = source[alias];
  //     }
  //   }
  // }
  // return target;
};

/**
 * 将阿里妈妈的iconfont.json文件读成想用的单色图标对象
 * @param json
 * @returns {{font_family: string, list: [], css_prefix_text: string}}
 */
export const analyzingIconForIconfont = (json) => {
  let font_family = "";
  let css_prefix_text = "";
  let list = [];
  if (json) {
    if (json.font_family) {
      font_family = json.font_family;
    }
    if (json.css_prefix_text) {
      css_prefix_text = json.css_prefix_text;
    }
    if (json.glyphs) {
      list = json.glyphs.map(function (value, index, array) {
        return font_family + " " + css_prefix_text + value.font_class;
      });
    }
  }
  return {
    font_family,
    css_prefix_text,
    list
  };
};

/**
 * 将阿里妈妈的iconfont.json文件读成想用的彩色图标对象
 * @param json
 * @returns {{font_family: string, list: [], css_prefix_text: string}}
 */
export const eIconSymbol = (json) => {
  let font_family = "";
  let css_prefix_text = "";
  let list = [];
  if (json) {
    if (json.font_family) {
      font_family = json.font_family;
    }
    if (json.css_prefix_text) {
      css_prefix_text = json.css_prefix_text;
    }
    if (json.glyphs) {
      list = json.glyphs.map(function (value, index, array) {
        return "#" + css_prefix_text + value.font_class;
      });
    }
  }
  return {
    font_family,
    css_prefix_text,
    list
  };
};

/****
 * 计算两个日期之间相差的天数
 */
export const getDiffDays = (earlyTime, lateTime) => {
  let diffDate = Math.abs(Date.parse(earlyTime) - Date.parse(lateTime)); //取相差毫秒数的绝对值
  let totalDays = Math.floor(diffDate / (1000 * 3600 * 24)); //向下取整

  return totalDays; //相差天数
};

/**
 * 比较两个时间先后，返回boolean，true: time晚于compareTime， false：time早于compareTime
 * @param {*} time
 * @param {*} compareTime
 * @returns
 */
export const returnCompareTime = (time, compareTime) => {
  return time - compareTime >= 0;
};

/**
 *
 * @param {*} hour
 * @param {*} minute
 * @param {*} isAdd
 * @returns
 *
 * 处理分钟数：59的情况
 * isAdd:  true 时间进1 分归0, false 时间不变 分-1
 */
export const returnHourMinute = (hour, minute, isAdd) => {
  if (Number(minute) != 59) {
    if (isAdd) {
      minute =
        minute[0] == 0 && minute[1] != 9
          ? `0${Number(minute) + 1}`
          : Number(minute) + 1;
    } else {
      if (minute === "00") {
        if (hour === "00") {
          minute = "00";
        } else {
          hour =
            hour[0] == 0
              ? `0${Number(hour) === 0 ? "0" : Number(hour) - 1}`
              : Number(hour) - 1;
          minute = 59;
        }
      } else {
        minute =
          minute[0] == 0
            ? `0${Number(minute) === 0 ? "0" : Number(minute) - 1}`
            : Number(minute) - 1;
      }
    }
  } else {
    if (isAdd) {
      minute = Number(hour) + 1 == 24 ? "59" : "00";
      hour =
        hour[1] == 0 && hour[2] != 9
          ? `0${Number(hour) + 1}`
          : Number(hour) + 1 == 24
            ? "23"
            : Number(hour) + 1;
    } else {
      minute = 58;
    }
  }
  if (typeof hour === "string") {
    hour = hour.replace(/\s+/g, "");
  }
  return `${hour}:${minute}`;
};

/**
 * 千分位处理
 */
export const returnThousandDigit = (value, precision = 2, splitDesc = ",") => {
  // const str = value.toString().includes(".")
  //   ? value.toFixed(precision)
  //   : value.toFixed(0);
  const str = Number(value).toFixed(precision);
  const reg = str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
  return str.replace(reg, "$1" + splitDesc);
};

/**
 * conversionType: 1 体积 0重量
 * 体积：立方米转化升
 * 重量：公斤转化吨
 */
export const volumeOrWeightConversion = (conversionType, value) => {
  if (conversionType) return value * 1000;
  else return (value / 1000).toFixed(2);
};

/**
 *
 * @param {*} arg1
 * @param {*} arg2
 * @returns {*}
 *
 * 处理小数位相加
 */
export const floatAdd = (arg1, arg2) => {
  var r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return (arg1 * m + arg2 * m) / m;
};

/**
 * @returns 
 * 异步加载百度地图
 */
export function SmallMapInit () {
  const AK = 'ODRrLKkspHGO73K6XdiPnXxmqGWYP8V8'
  const BMap_URL = 'https://api.map.baidu.com/api?v=2.0&ak=' + AK + '&s=1&callback=onBMapCallback'
  return new Promise((resolve) => {
    // 如果已加载直接返回
    if (typeof BMap !== 'undefined') {
      resolve(BMap)
      return true
    }
    // 百度地图异步加载回调处理
    window.onBMapCallback = function () {
      resolve(BMap)
    }
    // 插入script脚本
    let scriptNode = document.createElement('script')
    scriptNode.setAttribute('type', 'text/javascript')
    scriptNode.setAttribute('src', BMap_URL)
    document.body.appendChild(scriptNode)
  })
}

export const downLoadFile = async (url) => {
  const fileName = url.slice(url.lastIndexOf('/') + 1);
  try {
    const res = await fetch(url);
    const blob = await res.blob();
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    window.URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  } catch (error) {
    console.error(error);
  }
};


/**
 * 判断是否为空
 */
export function validatenull (val) {
  if (typeof val === 'boolean') {
    return false;
  }
  if (typeof val === 'number') {
    return false;
  }
  if (val instanceof Array) {
    if (val.length === 0) return true;
  } else if (val instanceof Object) {
    if (JSON.stringify(val) === '{}') return true;
  } else {
    if (val === 'null' || val === null || val === 'undefined' || val === undefined || val === '') return true;
    return false;
  }
  return false;
}

/**
 * 使用encodeURIComponent转换图片地址
 * */

function getFileNameFromUrl (url) {
  return url.substring(url.lastIndexOf('/') + 1);
}

export function encodeAndReplaceFileNameInUrl (url) {
  if (url.includes("?Expires")) {
    url = url.substring(0, url.lastIndexOf('?'));
  }
  const fileName = getFileNameFromUrl(url);
  const encodedFileName = encodeURIComponent(fileName);
  const replacedUrl = url.replace(fileName, encodedFileName);
  return replacedUrl
}